// Formatting utilities

/**
 * Format file size in bytes to human readable string
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}

/**
 * Format duration in seconds to human readable string
 */
export function formatDuration(seconds: number): string {
  if (seconds < 0) return '00:00';

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes
      .toString()
      .padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }

  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}

/**
 * Format duration in milliseconds to human readable string
 */
export function formatDurationMs(milliseconds: number): string {
  return formatDuration(milliseconds / 1000);
}

/**
 * Format date to relative time string
 */
export function formatRelativeTime(date: Date): string {
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60) {
    return '刚刚';
  }

  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }

  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  }

  const diffInDays = Math.floor(diffInHours / 24);
  if (diffInDays < 7) {
    return `${diffInDays}天前`;
  }

  const diffInWeeks = Math.floor(diffInDays / 7);
  if (diffInWeeks < 4) {
    return `${diffInWeeks}周前`;
  }

  const diffInMonths = Math.floor(diffInDays / 30);
  if (diffInMonths < 12) {
    return `${diffInMonths}个月前`;
  }

  const diffInYears = Math.floor(diffInDays / 365);
  return `${diffInYears}年前`;
}

/**
 * Format date to local string
 */
export function formatDate(date: Date, options?: Intl.DateTimeFormatOptions): string {
  const defaultOptions: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  };

  return date.toLocaleDateString('zh-CN', { ...defaultOptions, ...options });
}

/**
 * Format number with thousands separator
 */
export function formatNumber(num: number): string {
  return new Intl.NumberFormat('zh-CN').format(num);
}

/**
 * Format percentage
 */
export function formatPercentage(value: number, decimals: number = 1): string {
  return `${value.toFixed(decimals)}%`;
}

/**
 * Format bitrate
 */
export function formatBitrate(bitrate: number): string {
  if (bitrate < 1000) {
    return `${bitrate} kbps`;
  }

  return `${(bitrate / 1000).toFixed(1)} Mbps`;
}

/**
 * Format frame rate
 */
export function formatFrameRate(fps: number): string {
  return `${fps} fps`;
}

/**
 * Format resolution
 */
export function formatResolution(width: number, height: number): string {
  return `${width} × ${height}`;
}

/**
 * Format aspect ratio
 */
export function formatAspectRatio(width: number, height: number): string {
  const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
  const divisor = gcd(width, height);

  return `${width / divisor}:${height / divisor}`;
}

/**
 * Format compression ratio
 */
export function formatCompressionRatio(originalSize: number, newSize: number): string {
  if (originalSize === 0) return '0%';

  const ratio = ((originalSize - newSize) / originalSize) * 100;
  const sign = ratio >= 0 ? '-' : '+';

  return `${sign}${Math.abs(ratio).toFixed(1)}%`;
}

/**
 * Format processing speed
 */
export function formatProcessingSpeed(
  currentFrame: number,
  totalFrames: number,
  timeElapsed: number
): string {
  if (timeElapsed === 0 || currentFrame === 0) return '0x';

  const framesPerSecond = currentFrame / timeElapsed;
  const videoFps = totalFrames / (totalFrames / 30); // Assume 30fps for calculation
  const speed = framesPerSecond / videoFps;

  return `${speed.toFixed(1)}x`;
}

/**
 * Format ETA (Estimated Time of Arrival)
 */
export function formatETA(seconds: number): string {
  if (seconds <= 0) return '即将完成';

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  if (hours > 0) {
    return `剩余 ${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds
      .toString()
      .padStart(2, '0')}`;
  }

  if (minutes > 0) {
    return `剩余 ${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  }

  return `剩余 ${remainingSeconds}秒`;
}

/**
 * Format task status to Chinese
 */
export function formatTaskStatus(status: string): string {
  const statusMap: Record<string, string> = {
    pending: '等待中',
    queued: '排队中',
    processing: '处理中',
    completed: '已完成',
    failed: '失败',
    canceled: '已取消',
    paused: '已暂停',
  };

  return statusMap[status] || status;
}

/**
 * Format user role to Chinese
 */
export function formatUserRole(role: string): string {
  const roleMap: Record<string, string> = {
    user: '用户',
    admin: '管理员',
    moderator: '审核员',
  };

  return roleMap[role] || role;
}

/**
 * Format subscription plan to Chinese
 */
export function formatSubscriptionPlan(plan: string): string {
  const planMap: Record<string, string> = {
    free: '免费版',
    basic: '基础版',
    pro: '专业版',
    enterprise: '企业版',
  };

  return planMap[plan] || plan;
}

/**
 * Truncate text to specified length
 */
export function truncateText(text: string, maxLength: number, suffix: string = '...'): string {
  if (text.length <= maxLength) return text;

  return text.substring(0, maxLength - suffix.length) + suffix;
}

/**
 * Format file name for display
 */
export function formatFileName(fileName: string, maxLength: number = 30): string {
  if (fileName.length <= maxLength) return fileName;

  const extension = fileName.split('.').pop() || '';
  const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
  const truncatedName = nameWithoutExt.substring(0, maxLength - extension.length - 4);

  return `${truncatedName}...${extension}`;
}

/**
 * Format currency (if needed for subscription features)
 */
export function formatCurrency(amount: number, currency: string = 'CNY'): string {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency,
  }).format(amount);
}
